package com.alibaba.citrus.cr.sales.plan.functions.salesplan;

import com.alibaba.citrus.cr.common.util.CalculatePercentage;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.cr.sales.plan.functions.ability.model.DeletePlanCustomerAbilityRequest;
import com.alibaba.citrus.cr.sales.plan.functions.ability.model.DeletePlanScItemAbilityRequest;
import com.alibaba.citrus.cr.sales.plan.functions.ability.model.SalesPlanStatAbilityRequest;
import com.alibaba.citrus.cr.sales.plan.functions.ability.model.SalesPlanStatRequest;
import com.alibaba.citrus.cr.sales.plan.model.FullOrganizationValue;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanCustomerStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanCustomerStatRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanScItemStatRepository;
import com.alibaba.citrus.cr.sales.plan.repository.request.QueryPlanCustomerByAddressRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.DeleteSalesPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanScItemStatRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanCustomerStatRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryPlanScItemStatRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.converter.SalesPlanStatRequestConverter;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatCustomerSDO;
import com.alibaba.cz.base.model.enterprise.OrganizationSDO;
import com.alibaba.cz.base.tool.page.PageResult;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/9/20 3:01 下午
 */
@Component
public class SalesPlanStatAbility {

    @Resource
    private SalesPlanScItemStatRepository salesPlanScItemStatRepository;
    @Resource
    private SalesPlanCustomerStatRepository salesPlanCustomerStatRepository;
    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;
    @Resource
    private SalesPlanLineWriteService salesPlanLineWriteService;

    /**
     * 1、月度计划提报明细变更
     * a、将请求的集合，拆分为一个计划客户的，一个计划货品的（一般编辑 要么是客户维度编辑，要么是货品维度编辑）
     * if(statPlanCustomer)
     * 拆分得到的计划货品集合循环
     * 按planId + customerCode + customerAddress加锁
     * 查询计划客户信息 planId + customerCode + customerAddress，对比请求的计划客户，
     * if（存在）逐条更新计划客户的 ，合同数量，合同金额，计划量，计划金额，合同差价，合同满意度
     * if（不存在）批量插入计划客户表
     * 释放锁
     * if(statPlanScItem)
     * 按planId + scItemId加锁
     * 拆分得到的计划货品集合循环
     * 查询计划货品信息 planId + scItemId
     * if(不存在) 生成 业务员维度bizType:1 货品 维度数据
     * 部门维度  bizType:2 货品 维度数据
     * 渠道维度  bizType:3 货品 维度数据
     * 组织维度  bizType:4 货品 维度数据
     * 业务单位维度bizType:5货品 维度数据
     * 批量插入计划货品表
     * if(存在) 读取5条维度数据，逐条更新5个维度货品的数据
     * 合同数量，合同金额，计划量，合同差量，合同差额，合同满意度，上中下旬的计划量
     * 释放锁
     * <p>
     * 2、月度计划调整明细变更
     * <p>
     * 消息汇总
     * 月度计划明细变更汇总
     *
     * @param salesPlanStatAbilityRequest 请求
     * @return
     */
    public Boolean salesPlanStat(SalesPlanStatAbilityRequest salesPlanStatAbilityRequest) {
        if (salesPlanStatAbilityRequest.getIsAdjust()) {
            //TODO 汇总记录计算
        } else {
            List<SalesPlanStatRequest> salesPlanStatRequestList = salesPlanStatAbilityRequest.getSalesPlanStatRequestList();
            if (CollectionUtils.isEmpty(salesPlanStatRequestList)) {
                return true;
            }
            Map<String, List<SalesPlanStatRequest>> customerCollect = salesPlanStatRequestList.stream().collect(Collectors.toMap(this::planCustomerKey, Lists::newArrayList, (a, b) -> {
                a.addAll(b);
                return a;
            }));
            Map<String, List<SalesPlanStatRequest>> scItemCollect = salesPlanStatRequestList.stream().collect(Collectors.toMap(this::planScItemKey, Lists::newArrayList, (a, b) -> {
                a.addAll(b);
                return a;
            }));
            if (salesPlanStatAbilityRequest.getStatPlanCustomer()) {
                processPlanCustomer(customerCollect);
            }
            if (salesPlanStatAbilityRequest.getStatPlanScItem()) {
                //处理计划货品统计
                processPlanScItem(scItemCollect);
            }
        }
        return true;
    }

    private void processPlanScItem(Map<String, List<SalesPlanStatRequest>> scItemCollect) {

        for (Map.Entry<String, List<SalesPlanStatRequest>> entry : scItemCollect.entrySet()) {
            List<SalesPlanStatRequest> value = entry.getValue();
            FullOrganizationValue fullOrganization = new FullOrganizationValue();
            SalesPlanStatScItemSDO salesPlanScItemStatSDO = integratePlanScItem(value, fullOrganization);

            QueryPlanScItemStatRequest queryPlanScItemStatRequest = new QueryPlanScItemStatRequest();
            queryPlanScItemStatRequest.setPlanId(Long.parseLong(salesPlanScItemStatSDO.getPlanId()));
            queryPlanScItemStatRequest.setScItemId(salesPlanScItemStatSDO.getScItemId());
            List<String> bizIds = Lists.newArrayList(fullOrganization.getEmployeeId(),
                    fullOrganization.getOrgSalesDepartmentCode(),
                    fullOrganization.getOrgSalesChannelCode(),
                    fullOrganization.getOrgSalesOrganizationCode(),
                    fullOrganization.getOrgBusinessUnitCode());
            queryPlanScItemStatRequest.setBizIds(bizIds);
            queryPlanScItemStatRequest.setStart(0);
            queryPlanScItemStatRequest.setLimit(1000);
            PageResult<List<SalesPlanStatScItemSDO>> pageResult = salesPlanScItemStatRepository.batchQueryPlanScItemByBizId(queryPlanScItemStatRequest);
            List<SalesPlanStatScItemSDO> salesPlanScItemStatSDOList = pageResult.getContent();
            List<SalesPlanStatScItemSDO> batchPlanScItemRequest = Lists.newArrayList();
            if (CollectionUtils.isEmpty(salesPlanScItemStatSDOList)) {
                //每一个计划货品都是5条维度数据
                batchPlanScItemRequest = getBatchPlanScItemRequest(fullOrganization, salesPlanScItemStatSDO);
            } else {
                //更新5条维度数据
                Map<String, SalesPlanStatScItemSDO> collect = salesPlanScItemStatSDOList.stream().collect(Collectors.toMap(planScItem -> planScItemMapKey(planScItem.getBizType(), planScItem.getBizId()), salesPlanScItemStatSDO1 -> salesPlanScItemStatSDO1));
                List<String> bizTypeAndBizId = getBizTypeAndBizId(fullOrganization);

                for (String bizId : bizTypeAndBizId) {
                    SalesPlanStatScItemSDO planScItemStatSDO = collect.get(bizId);
                    String[] split = bizId.split("-");
                    if (planScItemStatSDO == null) {
                        batchPlanScItemRequest.add(calculateContractDifference(planScItemStatSDO, SalesStatBizTypeEnum.get(Integer.valueOf(split[0])), split[1]));
                    } else {
                        planScItemStatSDO.setMonthContractCount(planScItemStatSDO.getMonthContractCount() + salesPlanScItemStatSDO.getMonthContractCount());
                        planScItemStatSDO.setMonthContractMoney(planScItemStatSDO.getMonthContractMoney() + salesPlanScItemStatSDO.getMonthContractMoney());
                        planScItemStatSDO.setMonthCount(planScItemStatSDO.getMonthCount() + salesPlanScItemStatSDO.getMonthCount());
                        planScItemStatSDO.setMonthMoney(planScItemStatSDO.getMonthMoney() + salesPlanScItemStatSDO.getMonthMoney());
                        planScItemStatSDO.setMonthFirstCount(planScItemStatSDO.getMonthFirstCount() + salesPlanScItemStatSDO.getMonthFirstCount());
                        planScItemStatSDO.setMonthMiddleCount(planScItemStatSDO.getMonthMiddleCount() + salesPlanScItemStatSDO.getMonthMiddleCount());
                        planScItemStatSDO.setMonthLastCount(planScItemStatSDO.getMonthLastCount() + salesPlanScItemStatSDO.getMonthLastCount());
                        planScItemStatSDO.setM1RollingPlanCount(planScItemStatSDO.getM1RollingPlanCount() + salesPlanScItemStatSDO.getM1RollingPlanCount());
                        planScItemStatSDO.setM2RollingPlanCount(planScItemStatSDO.getM2RollingPlanCount() + salesPlanScItemStatSDO.getM2RollingPlanCount());
                        planScItemStatSDO.setM3RollingPlanCount(planScItemStatSDO.getM3RollingPlanCount() + salesPlanScItemStatSDO.getM3RollingPlanCount());

                        planScItemStatSDO.setContractDifferenceCount(planScItemStatSDO.getMonthCount() - planScItemStatSDO.getMonthContractCount());
                        //planScItemStatSDO.setContractDifferenceMoney(planScItemStatSDO.getMonthMoney() - planScItemStatSDO.getMonthContractMoney());
                        planScItemStatSDO.setContractSatisfaction(CalculatePercentage.retainTwo(planScItemStatSDO.getMonthMoney(), planScItemStatSDO.getMonthContractMoney()));
                        salesPlanScItemStatRepository.updatePlanScItem(planScItemStatSDO);
                    }
                }
            }
            if (!batchPlanScItemRequest.isEmpty()) {
                //TODO 批量保存纪元有问题
//                salesPlanStatRepository.batchCreatePlanScItem(batchPlanScItemRequest);
                for (SalesPlanStatScItemSDO sdo : batchPlanScItemRequest) {
                    salesPlanScItemStatRepository.createPlanScItem(sdo);
                }
            }

        }
    }

    private List<String> getBizTypeAndBizId(FullOrganizationValue fullOrganization) {
        List<String> result = Lists.newArrayList();
        result.add(planScItemMapKey(SalesStatBizTypeEnum.SALESMAN.getBizType(), fullOrganization.getEmployeeId()));
        result.add(planScItemMapKey(SalesStatBizTypeEnum.SALES_DEPARTMENT.getBizType(), fullOrganization.getOrgSalesDepartmentCode()));
        result.add(planScItemMapKey(SalesStatBizTypeEnum.SALES_CHANNEL.getBizType(), fullOrganization.getOrgSalesChannelCode()));
        result.add(planScItemMapKey(SalesStatBizTypeEnum.SALES_ORGANIZATION.getBizType(), fullOrganization.getOrgSalesOrganizationCode()));
        result.add(planScItemMapKey(SalesStatBizTypeEnum.BUSINESS_UNIT.getBizType(), fullOrganization.getOrgBusinessUnitCode()));
        return result;
    }


    private String planScItemMapKey(Integer bizType, String bizId) {
        return bizType + "-" + bizId;
    }

    private List<SalesPlanStatScItemSDO> getBatchPlanScItemRequest(FullOrganizationValue fullOrganization, SalesPlanStatScItemSDO salesPlanScItemStatSDO) {
        List<SalesPlanStatScItemSDO> batchCreateRequest = Lists.newArrayList();
        batchCreateRequest.add(calculateContractDifference(salesPlanScItemStatSDO, SalesStatBizTypeEnum.SALESMAN, fullOrganization.getEmployeeId()));
        batchCreateRequest.add(calculateContractDifference(salesPlanScItemStatSDO, SalesStatBizTypeEnum.SALES_DEPARTMENT, fullOrganization.getOrgSalesDepartmentCode()));
        batchCreateRequest.add(calculateContractDifference(salesPlanScItemStatSDO, SalesStatBizTypeEnum.SALES_CHANNEL, fullOrganization.getOrgSalesChannelCode()));
        batchCreateRequest.add(calculateContractDifference(salesPlanScItemStatSDO, SalesStatBizTypeEnum.SALES_ORGANIZATION, fullOrganization.getOrgSalesOrganizationCode()));
        batchCreateRequest.add(calculateContractDifference(salesPlanScItemStatSDO, SalesStatBizTypeEnum.BUSINESS_UNIT, fullOrganization.getOrgBusinessUnitCode()));
        return batchCreateRequest;
    }

    private SalesPlanStatScItemSDO calculateContractDifference(SalesPlanStatScItemSDO source, SalesStatBizTypeEnum bizType, String bizId) {
        SalesPlanStatScItemSDO target = new SalesPlanStatScItemSDO();
        BeanUtils.copyProperties(source, target);
        target.setBizType(bizType.getBizType());
        target.setBizId(bizId);
        target.setContractDifferenceCount(target.getMonthCount() - target.getMonthContractCount());
        //target.setContractDifferenceMoney(target.getMonthMoney() - target.getMonthContractMoney());
        target.setContractSatisfaction(CalculatePercentage.retainTwo(target.getMonthMoney(), target.getMonthContractMoney()));
        return target;

    }

    /**
     * 处理计划客户
     *
     * @param customerCollect
     */
    private void processPlanCustomer(Map<String, List<SalesPlanStatRequest>> customerCollect) {
        List<SalesPlanStatCustomerSDO> createRequest = Lists.newArrayList();
        for (Map.Entry<String, List<SalesPlanStatRequest>> entry : customerCollect.entrySet()) {
            //TODO 按planId + customerCode + customerAddress加锁，解决并发问题
            List<SalesPlanStatRequest> value = entry.getValue();
            SalesPlanStatCustomerSDO salesPlanCustomerStatSDO = integratePlanCustomer(value);

            QueryPlanCustomerByAddressRequest queryRequest = new QueryPlanCustomerByAddressRequest(salesPlanCustomerStatSDO.getPlanId(), salesPlanCustomerStatSDO.getCustomerCode(), salesPlanCustomerStatSDO.getCustomerAddress());
            SalesPlanStatCustomerSDO queryResult = salesPlanCustomerStatRepository.queryPlanCustomerByCustomerAddress(queryRequest);
            if (Objects.isNull(queryResult)) {
                //salesPlanCustomerStatSDO.setContractDifferenceMoney(salesPlanCustomerStatSDO.getMonthMoney() - salesPlanCustomerStatSDO.getMonthContractMoney());
                if (salesPlanCustomerStatSDO.getMonthContractMoney() != 0) {
                    salesPlanCustomerStatSDO.setContractSatisfaction(CalculatePercentage.retainTwo(salesPlanCustomerStatSDO.getMonthMoney(), salesPlanCustomerStatSDO.getMonthContractMoney()));
                }
                salesPlanCustomerStatSDO.setStatus(SalesPlanCustomerStatusEnum.TO_BE_REPLIED.getCode());
                createRequest.add(salesPlanCustomerStatSDO);
            } else {
                //更新（需要纪元提供version = version + 1）
                queryResult.setMonthContractCount(queryResult.getMonthContractCount() + salesPlanCustomerStatSDO.getMonthContractCount());
                queryResult.setMonthContractMoney(queryResult.getMonthContractMoney() + salesPlanCustomerStatSDO.getMonthContractMoney());
                queryResult.setMonthCount(queryResult.getMonthCount() + salesPlanCustomerStatSDO.getMonthCount());
                queryResult.setMonthMoney(queryResult.getMonthMoney() + salesPlanCustomerStatSDO.getMonthMoney());
                //queryResult.setContractDifferenceMoney(queryResult.getMonthMoney() - queryResult.getMonthContractMoney());
                queryResult.setContractSatisfaction(CalculatePercentage.retainTwo(queryResult.getMonthMoney(), queryResult.getMonthContractMoney()));
                queryResult.setStatus(SalesPlanCustomerStatusEnum.TO_BE_REPLIED.getCode());
                salesPlanCustomerStatRepository.updatePlanCustomer(queryResult);
            }
        }
        batchCreatePlanCustomer(createRequest);
    }

    private void batchCreatePlanCustomer(List<SalesPlanStatCustomerSDO> createRequest) {
//        if (createRequest.isEmpty()) {
//            return;
//        }
//        if (createRequest.size() <= 500) {
//            salesPlanStatRepository.batchCreatePlanCustomer(createRequest);
//        } else {
//            List<SalesPlanCustomerStatSDO> collect = createRequest.stream().limit(500).collect(Collectors.toList());
//            salesPlanStatRepository.batchCreatePlanCustomer(collect);
//
//            createRequest.removeAll(collect);
//            if (createRequest.size() <= 500) {
//                salesPlanStatRepository.batchCreatePlanCustomer(createRequest);
//                return;
//            }
//            batchCreatePlanCustomer(createRequest);
//        }
        createRequest.stream().forEach(item -> {
            salesPlanCustomerStatRepository.createPlanCustomer(item);
        });

    }

    /**
     * 同一个计划，货品，业务员下的数据
     *
     * @param value
     * @return
     */
    private SalesPlanStatScItemSDO integratePlanScItem(List<SalesPlanStatRequest> value, FullOrganizationValue fullOrganization) {
        SalesPlanStatScItemSDO result = new SalesPlanStatScItemSDO();

        boolean first = true;
        for (SalesPlanStatRequest request : value) {
            if (first) {
                fullOrganization.setOrgBusinessUnitCode(request.getOrgBusinessUnitCode());
                fullOrganization.setOrgSalesOrganizationCode(request.getOrgSalesOrganizationCode());
                fullOrganization.setOrgSalesChannelCode(request.getOrgSalesChannelCode());
                fullOrganization.setOrgSalesDepartmentCode(request.getOrgSalesDepartmentCode());
                fullOrganization.setEmployeeId(request.getManageEmployeeId());

                result.setPlanId(request.getPlanId());
                result.setBizType(SalesStatBizTypeEnum.SALESMAN.getBizType());
                result.setBizId(request.getManageEmployeeId());
                result.setScItemId(request.getScItemId());
                result.setScItemGroup(request.getScItemGroup());
                result.setCostInsuranceFreight(request.getCostInsuranceFreight());
//                result.setScItemLeafCategoryId(request.getScItemLeafCategoryId());
//                result.setScItemRootCategoryId(request.getScItemRootCategoryId());
//                result.setScItemName(request.getScItemName());
                result.setStatus(SalesPlanCustomerStatusEnum.TO_BE_REPLIED.getCode());
            }
            result.setMonthContractCount(result.getMonthContractCount() + request.getMonthContractCount());
            result.setMonthContractMoney(result.getMonthContractMoney() + request.getMonthContractMoney());
            result.setMonthCount(result.getMonthCount() + request.getMonthCount());
            result.setMonthMoney(result.getMonthMoney() + request.getMonthMoney());
            result.setMonthFirstCount(result.getMonthFirstCount() + request.getMonthFirstCount());
            result.setMonthMiddleCount(result.getMonthMiddleCount() + request.getMonthMiddleCount());
            result.setMonthLastCount(result.getMonthLastCount() + request.getMonthLastCount());
            result.setM1RollingPlanCount(result.getM1RollingPlanCount() + request.getM1RollingPlanCount());
            result.setM2RollingPlanCount(result.getM2RollingPlanCount() + request.getM2RollingPlanCount());
            result.setM3RollingPlanCount(result.getM3RollingPlanCount() + request.getM3RollingPlanCount());
            first = false;
        }
        return result;
    }

    private SalesPlanStatCustomerSDO integratePlanCustomer(List<SalesPlanStatRequest> value) {
        SalesPlanStatCustomerSDO result = new SalesPlanStatCustomerSDO();
        boolean first = true;
        for (SalesPlanStatRequest request : value) {
            if (first) {
                result.setPlanId(request.getPlanId());
                //result.setAdjustId(request.getAdjustId());
                result.setCustomerCode(request.getCustomerCode());
                result.setCustomerAddress(request.getCustomerAddress());
                result.setManageEmployeeId(request.getManageEmployeeId());
                result.setChannelCode(request.getChannelCode());
                result.setOrgBusinessUnitCode(request.getOrgBusinessUnitCode());
                result.setOrgSalesOrganizationCode(request.getOrgSalesOrganizationCode());
                result.setOrgSalesChannelCode(request.getOrgSalesChannelCode());
                result.setOrgSalesDepartmentCode(request.getOrgSalesDepartmentCode());
                //冗余信息
/*                result.setCustomerName(request.getCustomerName());
                result.setCustomerAddressName(request.getCustomerAddressName());
                result.setBondType(request.getBondType());*/
            }
            //明细合同量
            result.setMonthContractCount(result.getMonthContractCount() + request.getMonthContractCount());
            result.setMonthContractMoney(result.getMonthContractMoney() + request.getMonthContractMoney());
            result.setMonthCount(result.getMonthCount() + request.getMonthCount());
            result.setMonthMoney(result.getMonthMoney() + request.getMonthMoney());
            first = false;
        }
        return result;
    }

    private String planCustomerKey(SalesPlanStatRequest request) {
        return request.getPlanId() + "-" + request.getCustomerCode() + "-" + request.getCustomerAddress();
    }

    private String planScItemKey(SalesPlanStatRequest request) {
        return request.getPlanId() + "-" + request.getScItemId() + "-" + request.getManageEmployeeId();
    }


    /**
     * 删除计划客户
     *
     * @param deletePlanCustomerAbilityRequest
     * @return
     */
    public Boolean deletePlanCustomer(DeletePlanCustomerAbilityRequest deletePlanCustomerAbilityRequest) {
        /**
         * 1、查询要删除的计划客户 planId+planCustomerId+version
         *    if（不存在）抛异常
         *    计划客户状态是代发布/以发布状态不可删除 抛异常
         *
         *    if(不是调整计划客户,判断计划客户上是否有adjustId)
         *      更新计划客户状态为删除
         *      分页查询明细500
         *          List<明细> = 查询客户对应的所有计划明细（planId + customerCode + customerAddress ）
         *          更新计划明细状态为删除，条件：id
         *
         *          生产入参SalesPlanStatAbilityRequest，入参的SalesPlanStatRequest，对应合同量，合同金额，计划量，计划金额，上中下旬值为负数
         *          statPlanCustomer：false  statPlanScItem:true
         *          发消息：salesPlanStat
         *    else(是调整){TODO}
         *
         */
        //查询要删除的计划客户
        QueryPlanCustomerStatRequest queryPlanCustomerStatRequest = new QueryPlanCustomerStatRequest();
        queryPlanCustomerStatRequest.setId(deletePlanCustomerAbilityRequest.getId());
        SalesPlanStatCustomerSDO getSalesPlanCustomerResult = salesPlanCustomerStatRepository.getSalesPlanCustomer(queryPlanCustomerStatRequest);
        if (getSalesPlanCustomerResult != null) {
            //判断状态
            //计划客户状态是以发布状态不可删除 抛异常
            if (SalesPlanCustomerStatusEnum.PUBLISH.getCode() == getSalesPlanCustomerResult.getStatus()) {
                return false;
            }
            //判断是计划还是调整
            if (StringUtils.isNotEmpty(getSalesPlanCustomerResult.getPlanId())) {
                //计划修改状态
                SalesPlanStatCustomerSDO salesPlanCustomerStatSDO = new SalesPlanStatCustomerSDO();
                salesPlanCustomerStatSDO.setId(getSalesPlanCustomerResult.getId());
                salesPlanCustomerStatSDO.setStatus(SalesPlanCustomerStatusEnum.DELETE.getCode());
                SalesPlanCustomerStatEntity salesPlanCustomerStatEntity = SalesPlanCustomerStatEntity.of(salesPlanCustomerStatSDO);
                Boolean editBoolean = salesPlanCustomerStatEntity.planCustomerEdit();
                if (editBoolean) {
                    //成功 根据条件查询到明细数据
                    PageQueryPlanLineRequest pageQueryPlanLineRequest = new PageQueryPlanLineRequest();
                    pageQueryPlanLineRequest.setPlanId(getSalesPlanCustomerResult.getPlanId());
                    pageQueryPlanLineRequest.setCustomerAddress(getSalesPlanCustomerResult.getCustomerAddress());
                    //pageQueryPlanLineRequest.setCustomerCodes(Arrays.asList(getSalesPlanCustomerResult.getCustomerCode()));
                    PageResult<List<SalesPlanLineSDO>> listPageResult = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest);
                    List<Long> ids = new ArrayList<>();
                    listPageResult.getContent().forEach(salesPlanLineSDO -> {
                        //取到需要更新的ids
                        ids.add(salesPlanLineSDO.getId());
                    });
                    DeleteSalesPlanLineRequest deleteSalesPlanLineRequest = new DeleteSalesPlanLineRequest();
                    deleteSalesPlanLineRequest.setIds(ids);
                    //更新状态为删除
                    SalesPlanLineAbility salesPlanLineAbility = new SalesPlanLineAbility();
                    Boolean batchDeleteByIdsResult = salesPlanLineAbility.batchDeleteByIds(ids);
                    if (batchDeleteByIdsResult) {
                        //成功
                        SalesPlanStatAbilityRequest salesPlanStatAbilityRequest = SalesPlanStatRequestConverter.deletePlanCustomerConverter(listPageResult.getContent());
                        Boolean aBoolean = salesPlanStat(salesPlanStatAbilityRequest);
                        //todo 发送汇总消息
                    }
                }
                return false;
            } else {
                //调整 TODO
            }
        } else {
            //为空
            return false;
        }
        return true;
    }

    /**
     * 删除计划货品
     *
     * @param deletePlanScItemAbilityRequest
     * @return
     */
    public Boolean deletePlanScItem(DeletePlanScItemAbilityRequest deletePlanScItemAbilityRequest) {
        /**
         * 1、查询要删除的计划货品 planId+planScItemId+version
         *    if（不存在）抛异常
         *    计划货品状态是代发布/以发布状态不可删除 抛异常
         *
         *    if（不是调整计划客户,判断计划货品上是否有adjustId）
         *      按planId + scItemId加锁
         *          得到bizType,bizId。获取要删除的货品维度
         *          更新计划货品状态为删除
         *              查询bizType比当前小的计划货品数据，状态更新为删除
         *      释放锁
         *      分页查询明细500
         *          List<明细> = 查询货品对应的明细，条件planId + scItemId + (bizId)
         *          更新计划明细状态为删除，条件Id
         *          生产入参SalesPlanStatAbilityRequest，入参的SalesPlanStatRequest，对应合同量，合同金额，计划量，计划金额，上中下旬值为负数
         *          statPlanCustomer：true  statPlanScItem:false
         *          发消息：salesPlanStat
         *    else(是调整)TODO
         *
         *
         */
        //查询要删除的计划货品
      /*  QueryPlanScItemStatRequest queryPlanScItemStatRequest = new QueryPlanScItemStatRequest();
        queryPlanScItemStatRequest.setId(deletePlanScItemAbilityRequest.getId());
        SalesPlanStatScItemSDO getSalesPlanScItemResult = salesPlanScItemStatRepository.getSalesPlanScItem(queryPlanScItemStatRequest);
        if (StringUtils.isEmpty(getSalesPlanScItemResult.getAdjustId())) {
            //计划货品状态是代发布/以发布状态不可删除 抛异常
            if (SalesPlanScItemStatusEnum.PUBLISH.getCode().equals(getSalesPlanScItemResult.getStatus())) {
                return false;
            }
            //if（判断计划货品上是否有adjustId）
            if (StringUtils.isNotEmpty(getSalesPlanScItemResult.getPlanId())) {
                //得到bizType,bizId。获取要删除的货品维度
                Integer bizType = getSalesPlanScItemResult.getBizType();
                String bizId = getSalesPlanScItemResult.getBizId();
                //1：业务员货品汇总 2：销售部门货品汇总 3：销售渠道货品汇总 4：销售组织货品汇总 5：业务单元货品汇总
                if (SalesStatBizTypeEnum.SALESMAN.getBizType() == bizType) {
                    //业务员货品汇总
                    SalesPlanStatScItemSDO salesPlanScItemStatSDO = new SalesPlanStatScItemSDO();
                    salesPlanScItemStatSDO.setIds(Arrays.asList(getSalesPlanScItemResult.getId()));
                    salesPlanScItemStatSDO.setStatus(SalesPlanScItemStatusEnum.DELETE.getCode());
                    SalesPlanScItemStatEntity salesPlanScItemStatEntity = SalesPlanScItemStatEntity.of(salesPlanScItemStatSDO);
                    Boolean batchPlanScItemEditBoolean = salesPlanScItemStatEntity.batchPlanScItemEdit();
                    if (batchPlanScItemEditBoolean) {
                        //List<明细> = 查询货品对应的明细，条件planId + scItemId + (bizId)
                        PageQueryPlanLineRequest pageQueryPlanLineRequest = new PageQueryPlanLineRequest();
                        pageQueryPlanLineRequest.setPlanId(getSalesPlanScItemResult.getPlanId());
                        //pageQueryPlanLineRequest.setScItemIds(Arrays.asList(getSalesPlanScItemResult.getScItemId()));
                        PageResult<List<SalesPlanLineSDO>> listPageResult = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest);
                        List<Long> ids = new ArrayList<>();
                        listPageResult.getContent().forEach(salesPlanLineSDO -> {
                            ids.add(salesPlanLineSDO.getId());
                        });
                        DeleteSalesPlanLineRequest deleteSalesPlanLineRequest = new DeleteSalesPlanLineRequest();
                        deleteSalesPlanLineRequest.setIds(ids);
                        //更新状态为删除
                        Result<Boolean> booleanResult = salesPlanLineWriteService.deleteSalesPlanLine(deleteSalesPlanLineRequest);
                        if (booleanResult.getResult()) {
                            //成功
                            SalesPlanStatAbilityRequest salesPlanStatAbilityRequest = SalesPlanStatRequestConverter.deletePlanScItemConverter(listPageResult.getContent());
                            //TODO 发消息
                        }
                    }
                } else {
                    //2：销售部门货品汇总 3：销售渠道货品汇总 4：销售组织货品汇总 5：业务单元货品汇总
                    QueryPlanCustomerStatRequest queryPlanCustomerStatRequest = new QueryPlanCustomerStatRequest();
                    queryPlanCustomerStatRequest.setId(bizId);
                    List<OrganizationSDO> allChildOrganizations = salesPlanScItemStatRepository.getAllChildOrganizations(queryPlanCustomerStatRequest);
                    allChildOrganizations.forEach(organizationSDO -> {
                        //删除月度计划明细
                        //start
                        Integer type = organizationSDO.getType();
                        PageQueryPlanLineRequest pageQueryPlanLineRequest = new PageQueryPlanLineRequest();
                        if (OrganizationTypeEnum.COMPANY.getCode() == type) {
                            //分子公司
                            pageQueryPlanLineRequest.setOrgBusinessUnitCode(organizationSDO.getId());
                        } else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode() == type) {
                            //销售组织
                            pageQueryPlanLineRequest.setOrgSalesOrganizationCode(organizationSDO.getId());
                        } else if (OrganizationTypeEnum.SALES_CHANNEL.getCode() == type) {
                            //销售渠道
                            pageQueryPlanLineRequest.setOrgSalesChannelCode(organizationSDO.getId());
                        } else if (OrganizationTypeEnum.SALES_DEPARTMRNT.getCode() == type) {
                            //销售部门
                            pageQueryPlanLineRequest.setOrgSalesDepartmentCode(organizationSDO.getId());
                        }
                        //List<明细> = 查询货品对应的明细，条件planId + scItemId + (bizId)
                        pageQueryPlanLineRequest.setPlanId(getSalesPlanScItemResult.getPlanId());
                        //pageQueryPlanLineRequest.setScItemIds(Arrays.asList(getSalesPlanScItemResult.getScItemId()));
                        PageResult<List<SalesPlanLineSDO>> listPageResult = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest);
                        List<Long> ids = new ArrayList<>();
                        listPageResult.getContent().forEach(salesPlanLineSDO -> {
                            ids.add(salesPlanLineSDO.getId());
                        });
                        DeleteSalesPlanLineRequest deleteSalesPlanLineRequest = new DeleteSalesPlanLineRequest();
                        deleteSalesPlanLineRequest.setIds(ids);
                        //更新状态为删除
                        Result<Boolean> booleanResult = salesPlanLineWriteService.deleteSalesPlanLine(deleteSalesPlanLineRequest);
                        if (booleanResult.getResult()) {
                            //成功
                            SalesPlanStatAbilityRequest salesPlanStatAbilityRequest = SalesPlanStatRequestConverter.deletePlanScItemConverter(listPageResult.getContent());
                            //TODO 发消息
                        }
                        //end


                        //删除计划货品
                        //start
                        //先删除最高层
                        SalesPlanStatScItemSDO salesPlanScItemStatSDO = new SalesPlanStatScItemSDO();
                        List<Long> scItemIds = new ArrayList<>();
                        scItemIds.add(getSalesPlanScItemResult.getId());
                        salesPlanScItemStatSDO.setIds(scItemIds);
                        //获取子孙组织进行删除
                        if (organizationSDO.getChildren().size() > 0) {
                            organizationSDO.getChildren().forEach(organizationSDO1 -> {
                                //销售组织
                                PageQueryPlanScItemStatRequest pageQueryPlanScItemStatRequest=new PageQueryPlanScItemStatRequest();
                                pageQueryPlanScItemStatRequest.setPlanId(getSalesPlanScItemResult.getPlanId());
                                scItemBizTypeConverter(pageQueryPlanScItemStatRequest,organizationSDO1);
                                PageResult<List<SalesPlanStatScItemSDO>> listPageResult1 = salesPlanScItemStatRepository.pageQueryPlanScItemList(pageQueryPlanScItemStatRequest);
                                if (organizationSDO1.getChildren().size() > 0) {
                                    organizationSDO1.getChildren().forEach(organizationSDO2 -> {
                                        //渠道
                                        if (organizationSDO2.getChildren().size() > 0) {
                                            organizationSDO2.getChildren().forEach(organizationSDO3 -> {
                                                //部门
                                            });
                                        }
                                    });
                                }
                            });
                        }
                        salesPlanScItemStatSDO.setStatus(SalesPlanScItemStatusEnum.DELETE.getCode());
                        SalesPlanScItemStatEntity salesPlanScItemStatEntity = SalesPlanScItemStatEntity.of(salesPlanScItemStatSDO);
                        Boolean batchPlanScItemEditBoolean = salesPlanScItemStatEntity.batchPlanScItemEdit();

                        //end
                    });
                }
                //计划 按planId + scItemId加锁
                //释放锁
            } else {
                //调整 TODO
            }
        } else {
            //为空
            return false;
        }*/
        return true;
    }

    private void scItemBizTypeConverter(PageQueryPlanScItemStatRequest pageQueryPlanScItemStatRequest, OrganizationSDO organizationSDO){
        /*
        * bizType 1：业务员货品汇总 2：销售部门货品汇总 3：销售渠道货品汇总 4：销售组织货品汇总 5：业务单元货品汇总
        * */
        /*if (OrganizationTypeEnum.COMPANY.getCode()==organizationSDO.getType()){
            pageQueryPlanScItemStatRequest.setBizType(5);
            pageQueryPlanScItemStatRequest.setBizId(organizationSDO.getId());
        }else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode()==organizationSDO.getType()){
            pageQueryPlanScItemStatRequest.setBizType(4);
            pageQueryPlanScItemStatRequest.setBizId(organizationSDO.getId());
        }else if (OrganizationTypeEnum.SALES_CHANNEL.getCode()==organizationSDO.getType()){
            pageQueryPlanScItemStatRequest.setBizType(3);
            pageQueryPlanScItemStatRequest.setBizId(organizationSDO.getId());
        }else if (OrganizationTypeEnum.SALES_DEPARTMRNT.getCode()==organizationSDO.getType()){
            pageQueryPlanScItemStatRequest.setBizType(2);
            pageQueryPlanScItemStatRequest.setBizId(organizationSDO.getId());
        }*/
    }
}
